package api

import (
	"blog/app/common"
	albumModel "blog/app/model/album"
	"blog/app/request/album"
	"blog/core/request"
)

type AlbumApi struct {
}

// Lists , 获得相册列表
func (a AlbumApi) Lists(req request.InterfaceRequest) {
	param := &album.Lists{
		Page:  req.GetIntDefault("page", 1),
		Limit: req.GetIntDefault("Limit", 10),
	}

	lists, count := ServiceGroup.Album.GetList(param)
	req.Response().Message("查询成功").Count(count).Data(lists).Success()
}

// Create , 创建相册
func (a AlbumApi) Create(req request.InterfaceRequest) {
	param := &album.Create{
		Name:     req.InputStr("name"),
		Describe: req.InputStringDefault("describe", ""),
	}

	if err := req.Validate().Check(param); err != nil {
		req.Response().Message(err.Error()).Error()
		return
	}

	req.Response().Message("创建成功").WithErr(ServiceGroup.Album.Create(param))
}

// Edit , 编辑
func (a AlbumApi) Edit(req request.InterfaceRequest) {
	id := req.ParamInt("id")
	param := &albumModel.EditReqAlbum{
		Path: req.InputStringDefault("path", ""),
		Name: req.InputStr("name"),
	}

	if err := req.Validate().Check(param); err != nil {
		req.Response().Message(err.Error()).Error()
		return
	}

	req.Response().WithErr(ServiceGroup.Album.Edit(id, param))
}

// Del , 删除相册
func (a AlbumApi) Del(req request.InterfaceRequest) {
	id := req.ParamInt("id")
	req.Response().WithErr(ServiceGroup.Album.Del(id))
}

// Upload ， 上传图片到指定图片
func (a AlbumApi) Upload(req request.InterfaceRequest) {
	id := req.ParamInt("id")
	path := req.InputStr("path")
	context := req.GetContext()
	fileOrigin, err := context.FormFile("file")
	if path == "" && err != nil {
		req.Response().Message("文件路径不能为空").Error()
		return
	}

	if err == nil {
		render, _ := fileOrigin.Open()
		defer render.Close()
		hash, err := common.Upload.UploadHash(fileOrigin.Filename, fileOrigin.Size, render)
		if err != nil {
			req.Response().Message(err.Error()).Error()
			return
		}
		path = hash
	}

	req.Response().WithErr(ServiceGroup.Album.Upload(id, path))
}

// GetAlbumImages , 获得指定相册下的图片
func (a AlbumApi) GetAlbumImages(req request.InterfaceRequest) {
	id := req.ParamInt("aid")
	lists, count := ServiceGroup.AlbumImage.GetLists(id)
	req.Response().Message("查询成功").Count(count).Data(lists).Success()
}

// DelAlbumImages , 删除指定相册下的图片
func (a AlbumApi) DelAlbumImages(req request.InterfaceRequest) {
	aid := req.ParamInt("aid")
	id := req.ParamInt("id")
	req.Response().Message("删除成功").WithErr(ServiceGroup.AlbumImage.Del(aid, id))
}
